package com.ioftv.controller;

import com.ioftv.common.Result;
import com.ioftv.dto.LoginRequest;
import com.ioftv.dto.LoginResponse;
import com.ioftv.dto.UpdateUserProfileRequest;
import com.ioftv.entity.SysUser;
import com.ioftv.service.SysUserService;
import com.ioftv.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户控制器
 * 处理用户登录、退出、新增、修改等操作
 */
@RestController
@RequestMapping("/admin")
public class UserController {

    @Autowired
    private SysUserService sysUserService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 登录接口
     * POST /admin/login
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody LoginRequest request) {
        // 参数校验
        if (request.getUsername() == null || request.getUsername().trim().isEmpty()) {
            return Result.error("用户名不能为空");
        }
        if (request.getPassword() == null || request.getPassword().trim().isEmpty()) {
            return Result.error("密码不能为空");
        }

        // 查询用户
        SysUser user = sysUserService.getByUsername(request.getUsername());
        if (user == null) {
            return Result.error("用户名或密码错误");
        }

        // 验证密码（明文比对）
        if (!user.getPassword().equals(request.getPassword())) {
            return Result.error("用户名或密码错误");
        }

        // 检查用户状态
        if (user.getStatus() == 0) {
            return Result.error("账号已被禁用");
        }

        // 生成JWT Token
        String token = jwtUtil.generateToken(user.getId(), user.getUsername(), user.getRole());

        // 构造响应数据
        LoginResponse response = new LoginResponse();
        response.setToken(token);

        LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setNickname(user.getNickname());
        userInfo.setRole(user.getRole());
        userInfo.setCompanyName(user.getCompanyName()); // 添加公司名称
        response.setUser(userInfo);

        return Result.success(response);
    }

    /**
     * 退出登录接口
     * POST /admin/logout
     */
    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        // 从请求中获取Token
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            // 实际项目中可以将Token加入黑名单
            // 这里简化处理，直接返回成功
        }
        return Result.success(null);
    }

    /**
     * 获取用户信息接口
     * GET /admin/userInfo
     */
    @GetMapping("/userInfo")
    public Result<LoginResponse.UserInfo> getUserInfo(HttpServletRequest request) {
        // 从请求属性中获取用户信息
        Long userId = (Long) request.getAttribute("userId");
        String username = (String) request.getAttribute("username");
        String role = (String) request.getAttribute("role");
        
        // 查询用户详细信息
        SysUser user = sysUserService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setNickname(user.getNickname());
        userInfo.setRole(user.getRole());
        userInfo.setCompanyName(user.getCompanyName()); // 添加公司名称
        return Result.success(userInfo);
    }

    /**
     * 新增用户
     * POST /admin/user
     */
    @PostMapping("/user")
    public Result<SysUser> addUser(@RequestBody SysUser user, HttpServletRequest request) {
        // 从请求属性中获取当前用户信息
        String currentUsername = (String) request.getAttribute("username");
        String currentRole = (String) request.getAttribute("role");
        
        // 参数校验
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            return Result.error("用户名不能为空");
        }
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            return Result.error("密码不能为空");
        }

        // 检查用户名是否已存在
        SysUser existUser = sysUserService.getByUsername(user.getUsername());
        if (existUser != null) {
            return Result.error("用户名已存在");
        }

        // 设置默认值
        if (user.getRole() == null || user.getRole().trim().isEmpty()) {
            user.setRole("ADMIN");
        }
        if (user.getStatus() == null) {
            user.setStatus(1);
        }

        // 保存用户
        boolean success = sysUserService.save(user);
        if (success) {
            return Result.success(user);
        } else {
            return Result.error("新增用户失败");
        }
    }

    /**
     * 修改用户
     * PUT /admin/user/{id}
     */
    @PutMapping("/user/{id}")
    public Result<SysUser> updateUser(@PathVariable Long id, @RequestBody SysUser user, HttpServletRequest request) {
        // 从请求属性中获取当前用户信息
        String currentUsername = (String) request.getAttribute("username");
        String currentRole = (String) request.getAttribute("role");
        
        // 检查用户是否存在
        SysUser existUser = sysUserService.getById(id);
        if (existUser == null) {
            return Result.error("用户不存在");
        }

        // 设置ID
        user.setId(id);

        // 如果修改了用户名，检查是否重复
        if (user.getUsername() != null && !user.getUsername().equals(existUser.getUsername())) {
            SysUser userByUsername = sysUserService.getByUsername(user.getUsername());
            if (userByUsername != null && !userByUsername.getId().equals(id)) {
                return Result.error("用户名已存在");
            }
        }

        // 更新用户
        boolean success = sysUserService.updateById(user);
        if (success) {
            return Result.success(sysUserService.getById(id));
        } else {
            return Result.error("修改用户失败");
        }
    }
    
    /**
     * 更新用户信息接口
     * POST /admin/user/profile
     */
    @PostMapping("/user/profile")
    public Result<LoginResponse.UserInfo> updateUserProfile(@RequestBody UpdateUserProfileRequest request, HttpServletRequest httpRequest) {
        // 从请求属性中获取当前用户信息
        Long userId = (Long) httpRequest.getAttribute("userId");
        String username = (String) httpRequest.getAttribute("username");
        String role = (String) httpRequest.getAttribute("role");
        
        // 参数校验
        if (request.getCurrentPassword() == null || request.getCurrentPassword().trim().isEmpty()) {
            return Result.error("当前密码不能为空");
        }
        
        // 查询用户
        SysUser user = sysUserService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 验证当前密码
        if (!user.getPassword().equals(request.getCurrentPassword())) {
            return Result.error("当前密码错误");
        }
        
        // 如果提供了新密码，则更新密码
        if (request.getNewPassword() != null && !request.getNewPassword().trim().isEmpty()) {
            // 验证新密码长度
            if (request.getNewPassword().length() < 6) {
                return Result.error("新密码长度不能少于6位");
            }
            user.setPassword(request.getNewPassword());
        }
        
        // 如果提供了公司名称，则更新公司名称
        if (request.getCompanyName() != null && !request.getCompanyName().trim().isEmpty()) {
            user.setCompanyName(request.getCompanyName());
        }
        
        // 更新用户信息
        boolean success = sysUserService.updateById(user);
        if (success) {
            LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo();
            userInfo.setId(user.getId());
            userInfo.setUsername(user.getUsername());
            userInfo.setRole(user.getRole());
            userInfo.setCompanyName(user.getCompanyName());
            return Result.success(userInfo);
        } else {
            return Result.error("更新用户信息失败");
        }
    }
}